package com.aoyy.action.order;

import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.sql.Timestamp;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ModelDriven;

import com.aoyy.action.BaseAction;
import com.aoyy.util.order.State;
import com.aoyy.util.Pagination;
import com.aoyy.util.StringFormatter;
import com.aoyy.model.OrderItem;
import com.aoyy.model.Order;
import com.aoyy.model.Product;
/**================================================================
 * <code>OrderAction</code> action for <code>Order</code>
 * @author Administrator
 * @date 2017-07-13
 * =============================================================== */
@Scope("prototype")
@Controller("orderAction")
public class OrderAction extends BaseAction implements ModelDriven<Order> {
  private static final long serialVersionUID = 7404692178864688202L;
  private Order order = new Order(); 
  private Pagination<Order> pagination; 
  
  public void setOrder(Order order) {
	this.order = order;  
  }
  public Order getOrder() {
	return order;  
  }
  
  public void setPagination(Pagination<Order> pagination) {
	this.pagination = pagination;  
  }
  public Pagination<Order> getPagination() {
	return pagination;  
  }
  
  @Override
  public Order getModel() {
	return order;
  }
  
  /**===========================================================
   * <code>add()<code> method for adding <code>order</code> 
   * @author this author
   * @date 2017-07-14
   * =========================================================== */
  public String add() {
	if (getCart().isEmpty()) {
	  return ERROR;
	}
	order.setRealName(getLoginUser().getRealName());
	order.setTel(getLoginUser().getTel());
	order.setAddress(getLoginUser().getAddress());
	return ADD;  
  }
  
  public String confirm() {
	if (order.getRealName() == null || order.getRealName().isEmpty()) {
      addFieldError("realName", "Consignee is required.");
      return ADD;
	} else if (order.getRealName().length() > 45) {
	  addFieldError("realName", "Consignee is required and to be no more than 45 characters.");
	  return ADD;
	}
	if (order.getTel() == null || order.getTel().isEmpty()) {
	  addFieldError("tel", "Tel is required.");
	  return ADD;
    } else if (order.getTel().length() < 8 || order.getTel().length() > 11) {
	  addFieldError("tel", "Tel is required to be between 8 and 11 digits.");
	  return ADD;
	}
	if (order.getAddress() == null || order.getAddress().isEmpty()) {
	  addFieldError("address", "Address is required.");
	  return ADD;
	} else if (order.getAddress().length() > 255) {
	  addFieldError("address", "Address is required and to be no more than 255 characters.");
	  return ADD;
    }	
	return "confirm";  
  }
 
  public String save() {
	if (getLoginUser() != null) {
	  Product product;
	  Float totalPrice = .0F;
	  Set<OrderItem> cart = getCart();
	  for (OrderItem orderItem: cart) {
		product = productDao.load(orderItem.getProduct().getProductId());
		product.setSalesVolume(product.getSalesVolume() + orderItem.getQuantity());
		productDao.update(product);
		totalPrice += orderItem.getQuantity() * orderItem.getProduct().getSalesPrice(); 
	  }
	  order.setOrderItems(cart);
	  order.setTotalPrice(totalPrice);
	  order.setOrderNo(StringFormatter.getOrderNo());
	  order.setUser(getLoginUser());
	  order.setState(State.DELIVERED);
	  order.setCreatedTime(Timestamp.valueOf(StringFormatter.getDateTimeStr()));
	  orderDao.save(order);
	  session.remove("cart");
	}
	return getOrdersByUser();
  }
  
  public String getOrdersByUser() {
	if (getLoginUser() != null) {
	  String where = "where user.userId = ?";
	  Object[] parameters = {getLoginUser().getUserId()};
	  Map<String, String> orderby = new HashMap<String, String>();
	  orderby.put("createdTime", "desc");
	  pagination = orderDao.query(where, parameters, orderby, pageNo, pageSize);
	}
	return LIST;  
  }
  
  public String list() {
	Map<String, String> orderby = new HashMap<String, String>();
	orderby.put("createdTime", "desc");
	StringBuffer buffer = new StringBuffer();
	List<Object> parameters = new ArrayList<Object>();
	if (order.getOrderNo() != null && !order.getOrderNo().isEmpty()) {
      buffer.append("orderNo = ?");
      parameters.add(order.getOrderNo());
	}
	if (order.getState() != null) {
	  if (parameters.size() > 0) {
		buffer.append(" and ");  
	  }
	  buffer.append("state = ?");
	  parameters.add(order.getState());
	}
	if (order.getUser() != null) {
      if (order.getUser().getUserName() != null && !order.getUser().getUserName().isEmpty()) {
    	if (parameters.size() > 0) {
    	  buffer.append(" and ");	
    	}
    	buffer.append("user.userName = ?");
    	parameters.add(order.getUser().getUserName());
      }
	  if (order.getUser().getRealName() != null && !order.getUser().getRealName().isEmpty()) {
		if (parameters.size() > 0) {
		  buffer.append(" and ");	
		}
		buffer.append("user.realName = ?");
		parameters.add(order.getUser().getRealName());
	  }
	}
	String where = buffer.length() > 0 ? "where " + buffer.toString() : ""; 
	pagination = orderDao.query(where, parameters.toArray(), orderby, pageNo, pageSize);
	return LIST;
  }
  
  public String select() {
	order = orderDao.load(order.getOrderId());
	return SELECT;  
  }
  
  public String update() {
	State state = order.getState();
	order = orderDao.load(order.getOrderId());
	order.setState(state);
	orderDao.update(order);
	return UPDATE;  
  }

}
